<template>
  <div class="outer">
    <section class="main">
      <div class="banner">
        <back-btn></back-btn>
        <img src="../assets/images/bannertrain.png"/>
      </div>
      <div class="listInfo">
        <div class="trainTitle">火 车</div>
        <div class="trainInfo">
          <exchange-city :cityGo="cityGo"
                         :cityBack="cityBack"
                         :cityGoObj="cityGoClassObj"
                         :cityBackObj="cityBackClassObj"
                         @selectCityGo="cityVueTrain"
                         @selectCityBack="cityVueTrain"
                         @exchangeCity="changeCity">
          </exchange-city>
          <date-select :calendarFromData="calendarFromData"
                       :weekFromData="weekFromData"
                       @dateFromSelect="popupCalendarVisible = true"></date-select>
          <!--日历组件-->
          <div v-transfer-dom>
            <Popup v-model="popupCalendarVisible" position="bottom" max-height="50%" style="background: none">
              <inline-calendar
                @on-select-single-date="onChangeFromDate"
                :show.sync="show"
                v-model="calendarData"
                :start-date="startDate"
                :end-date="endDate"
                :show-next-month="false"
                :show-last-month="false"
                :replace-text-list="{'TODAY':'今'}">
              </inline-calendar>
            </Popup>
          </div>
          <footer class="search">
            <div class="selectBtn"  @click="trainList" size="large" >搜索</div>
          </footer>
          <search-history :storageKey="searchHistoryKey" @historyClick="inputCity" ref="search-history"></search-history>
        </div>
      </div>
      <bottom-navbar leftIcon="iconfont icon-guoneihuochedingdan"
                     rightIcon="iconfont icon-liecheshike"
                     leftTitle="火车订单"
                     rightTitle="列车时刻"
                     @clickLeftBtn = "trainOrderClick"
                     @clickRightBtn = "trainMomentClick"></bottom-navbar>
    </section>
  </div>
</template>
<script>
  import date from '../components/date.vue';
  import { weeks } from '../lib/weeker.js'
  import { InlineCalendar, Popup, TransferDomDirective as TransferDom} from 'vux'
  import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'
  import exchangeCity from '../components/exchange-city.vue'
  import dateSelect from '../components/date-select.vue'
  import bottomNavbar from '../components/bottom-navbar.vue'
  import SearchHistory from './search-history.vue'
  import backBtn from '../components/backBtn.vue'
  import train from '@/data/train';
  export default {
    name: 'train2',
    data () {
      return {
        popupCalendarVisible: false,
        go: '出发地',
        back: '目的地',
        date1: '请选择乘车日期', // 页面上显示的日期
        weekToday: '',  // 星期几
        date: '',
        show:  false,
        text: 'loadIngText',
        searchHistoryKey: 'searchTrainHistory',
        calendarData:null
      }
    },
    components: {
      InlineCalendar,
      Popup,
      date,
      SearchHistory,
      bottomNavbar,
      backBtn,
      exchangeCity,
      dateSelect
    },
    directives: {
      TransferDom
    },
    methods: {
      onChangeFromDate(val) {
        this.$store.commit('CHANGEt_RAIN_GO_TIME', val)
        this.date = this.$store.state.train.travelTime;
        // 给老版本日历组件赋值显示当前active状态
        this.$store.state.train.openTime = val;
        this.popupCalendarVisible = false;
      },
      trainOrderClick: function () {
        $jump.to('common/all?type=T');
      },
      trainMomentClick: function () {
        this.$vux.toast.show({
          type: 'text',
          text: '暂未开放',
          time: 2000
        })
        return
      },
      //历史记录赋值  需要判断历史记录的时间与当前时间
      inputCity: function (item) {
        var goDate = item.travelTime, //出发时候的时间YYYY-MM-DD
            curTime = moment().format('YYYY-MM-DD'), // 当前时间格式
            curDate = +moment(),       // 当前时间戳
            hisDate = +moment(goDate); // 历史记录时间戳
        if(curDate < hisDate) {
          this.$store.state.train.date1 = item.date1;
          this.$store.state.train.weekToday = weeks(item.travelTime);
          this.calendarData = item.travelTime;   //日历插件赋值
          this.$store.state.train.travelTime = item.travelTime;
          this.$store.state.train.openTime = item.travelTime;  // 老版本日历插件赋值
        } else {
          this.$store.state.train.date1 = curTime.substring(5, 7) + '月' + curTime.substring(8, 10) + '日';
          this.$store.state.train.weekToday = '今天';
          this.calendarData = curTime;   //日历插件赋值
          this.$store.state.train.travelTime = curTime;
          this.$store.state.train.openTime = curTime;  // 老版本日历插件赋值
        }
        this.$store.state.train.go = item.go;
        this.$store.state.train.back = item.back;
      },
      //切换城市选择
      changeCity() {
        var store = this.$store.state.train;
        if(store.go !== '出发地' && store.back !== '目的地') {
          var change , change1;
          change = this.$store.state.train.go;
          this.$store.state.train.go = this.$store.state.train.back;
          this.$store.state.train.back = change;
          change1 = this.$store.state.train.fromCityCode;
          this.$store.state.train.fromCityCode = this.$store.state.train.toCityCode;
          this.$store.state.train.toCityCode = change1;
        }
      },
      //调用选择热门城市接口
      cityVueTrain(i) {
        this.$router.push({
          path: '/train/cityTrain',
          query: {
            go: i
          }
        })
      },
      trainList(){
        var that = this;
        if(this.$store.state.train.go == '出发地' || this.$store.state.train.go == '目的地' || this.$store.state.train.back == '出发地' || this.$store.state.train.back == '目的地'){
          that.$vux.toast.show({
            type: 'text',
            text: '信息填写不完整',
            time: 2000
          })
        } else if(this.$store.state.train.go == this.$store.state.train.back){
          that.$vux.toast.show({
            type: 'text',
            text: '目的地出发地相同',
            time: 2000
          })
        } else{
          that.$vux.loading.show({
            text: '加载中...'
          })
          //出发时间
          this.$store.state.train.train_date = this.date;//存储火车列表不更新的问题
          var trainSearchForm = {
            fromCity: this.$store.state.train.go, //出发城市
            fromCityCode: this.$store.state.train.fromCityCode,
            toCityCode: this.$store.state.train.toCityCode,
            toCity: this.$store.state.train.back, //到达城市
            travelTime: this.$store.state.train.travelTime, //出发时间
            transType: this.$store.state.train.transType, /** * 根据车型类型进行过滤： * * <pre> * 0 全部车型 * 1 城际、高铁、动车（G/D/C） * 2 特快、直达（T/Z） * 3 其他车型 * </pre> */
            sortNum: this.$store.state.train.sortNum,  /*火车票列表排序数： 1 最早出发， 2 最晚出发， 3 耗时最短*/
            isFilter:1
          };

          train.getTrainList(trainSearchForm,function (res) {
            // 存放历史记录的数据处理对象
            var curSearch = {
              'go': that.$store.state.train.go,
              'back': that.$store.state.train.back,
              'fromCityName': that.$store.state.train.fromCityName,
              'toCityName': that.$store.state.train.toCityName,
              'travelTime': that.$store.state.train.travelTime,
              'date1': that.$store.state.train.date1,
              'travelTime': that.$store.state.train.travelTime,
              'weekToday': that.$store.state.train.weekToday,
              'currentDate': that.$store.state.train.currentDate
            }
            that.$refs['search-history'].addHistory(curSearch);

            if(res.ticketList && res.ticketList.length <= 0){
              that.$vux.loading.hide();
              that.$vux.toast.show({
                type: 'text',
                text:  res.msg,
                time: 1000
              })
              return
            }
            if(res.msg == "") {
              that.$store.state.train.train_tanrey_off_on = false;
            }else{
              that.$store.state.train.train_tanrey_off_on = true;
              that.isFiltertext = res.msg;
            }
            that.$store.state.train.ticketList = res.ticketList || '';
            //星期列表
            that.$store.state.train.week = res.week;
            //拼接几月几号星期几
            that.$store.state.train.month = that.$store.state.train.travelTime.substring(5,7);
            that.$store.state.train.day = that.$store.state.train.travelTime.substring(8,10);
            for(var i=0;i<that.$store.state.train.week.length;i++){
              if(that.$store.state.train.week[i].flag == true){
                that.$store.state.train.Sunday  = '周' +  that.$store.state.train.week[i].week;
                that.$store.state.train.selected = that.$store.state.train.week[i].id;
              }
            }
            //综合数据初始化
            var train = that.$store.state.train;

            train.seatTypes = '';
            train.fromStations = '';
            train.toStations = '';
            train.fromTimeRanges = '';
            train.toTimeRanges = '';
            //综合筛选数据重组
            var arriveStationList = res.ticketList.arriveStationList;   //到达车站
            var fromStationList = res.ticketList.fromStationList;  //出发车站
            if(res.ticketList.length != 0){
              that.$store.commit('CLEAR_TRAIN_GO_CITY_NAME', []);
              for(var i=0 ; i<fromStationList.length; i++){
                var station = {
                  a:false
                };
                station.name = fromStationList[i];
                that.$store.state.train.tabInfo[1].tabInfos.push(station)
              }
              that.$store.commit('CLEAR_TRAIN_BACK_CITY_NAME', []);
              for(var i=0 ; i<arriveStationList.length; i++){
                var station = {
                  a:false
                };
                station.name = arriveStationList[i];
                that.$store.state.train.tabInfo[2].tabInfos.push(station)
              }
            }
            that.$vux.loading.hide();
            that.$router.push({
              path: '/train/trainList',
              query:{
                fromName: 'train'
              }
            })
          },function () {
            that.$vux.loading.hide();
            that.$router.push({
              name: 'error',
              params:{
                backName: 'train2',
              }
            });
          });
        }
      },
    },
    mounted() {
      var currentDate = this.$store.state.train.travelTime;
      var nowDate = moment().format('YYYY-MM-DD');
      if(!currentDate) {
        currentDate = nowDate;
      }
      this.calendarData = currentDate;
      //传给后台当前的时间
      var currentdate = nowDate;
      this.$store.state.train.currentDate =  currentdate;
      if(this.$store.state.train.onlyOne === 1) {
        // 一上来默认给今天时间 传给后台
        this.date = currentdate;   //同时也是时间插件绑定的数据
        this.$store.state.train.onlyOne = 2;
        //出发时间
        this.$store.state.train.travelTime = this.date;
      } else {
        this.date = this.$store.state.train.travelTime;
      }

      //获取首页差旅计划传递的数据 也可能是别的地方传过来数据
      var fromCity = this.$route.query.fromCity,
        toCity = this.$route.query.toCity,
        fromDate = this.$route.query.fromDate;
      if(fromDate && +moment(currentdate) < +moment(fromDate)) {
        this.date = fromDate;
        this.$store.state.train.travelTime = fromDate
        this.$store.state.train.openTime = fromDate;
      } else if(fromDate && +moment(currentdate) >= +moment(fromDate)) {
        this.date = currentdate;
        this.$store.state.train.travelTime = currentdate;
        this.$store.state.train.openTime = moment().format('YYYY-MM-DD');
      };
      if(fromCity) {
        this.$store.state.train.go = fromCity;
      }
      if(toCity) {
        this.$store.state.train.back = toCity;
      }
    },
    watch: {
      date(val,oldVal) {
        var year = val.substring(0,4);
        var mouth = val.substring(5,7);
        var day = val.substring(8,10);
        this.$store.state.train.date1 = mouth + '月' + day + '日';
        var tmpdate = new Date(year,mouth-1,day);
        tmpdate = tmpdate.getDay();
        this.$store.state.train.weekToday = weeks(this.date);
      }
    },
    computed:{
      startDate() {
        return moment().format('YYYY-MM-DD')
      },
      endDate() {
        return moment().add(1, 'M').add(1, 'd').format('YYYY-MM-DD');
      },
      calendarFromData() {
        return this.$store.state.train.date1;
      },
      weekFromData() {
        return this.$store.state.train.weekToday;
      },
      tab(){
        return this.$store.state.tab
      },
      cityGoClassObj() {
        return  this.cityGo =='出发地'|| this.cityGo  == '目的地' ? 'goBackActive' : ''
      },
      cityBackClassObj(){
        return this.cityBack =='目的地'|| this.cityBack == '出发地' ? 'goBackActive' : ''
      },
      cityGo() {
        return this.$store.state.train.go;
      },
      cityBack() {
        return this.$store.state.train.back;
      },
      trainData(){
        return this.$store.state.train
      },
      tabInfo(){
        return this.$store.state.train.tabInfo
      },
      train(){
        return this.$store.state.train
      }
    }
  }

</script>


<style rel="stylesheet/scss" lang="scss" scoped>
  .outer {
    position: relative;
    width: 100%;
    height: 100%;
    background-color: rgba(248, 248, 248, 1);
  }
  .main {
    padding-top:0;
    padding-bottom: 3.5rem;
    margin-bottom: .5rem;
  }
  .item {
    font-size: .9rem;
    height: 3rem;
    input[type=text]{
      font-size: .9rem;
      line-height: 3rem;
      height: 3rem;
    }
  }
  .active {
    border-bottom: 2px solid #0094db;
  }
  .goBack{
    display: flex;
    position: relative;
    line-height: 3rem;
    text-align: center;
    border-bottom: 1px solid #ddd;
    > span {
      display: inline-block;
      width: 33.33%;
      font-size: 1.05rem;
    }
    > span:first-child {
      position: absolute;
      left: 0;
      top: 0;
      transition: all .4s;
    }
    > span.left {
      position: absolute;
      left: 0!important;
      top: 0;
      transition: all .4s;
    }
    > span:nth-child(2) {
      position: absolute;
      left: 33.33%;
      top: 0;
    }
    > span:nth-child(3) {
      position: absolute;
      left: 66.66%;
      top: 0;
      transition: all .4s;
    }
    > span.right {
      position: absolute;
      left: 66.66% !important;
      top: 0;
      transition: all .4s;
    }
  }
  .search{
    padding-bottom: 1rem;
  }
  .selectBtn {
    margin: 2rem auto 0;
    color: #fff;
    width: 95%;
    height: 2.5rem;
    background-color: #46a1bb;
    font-size: 1.05rem;/*px*/
    text-align: center;
    line-height: 2.5rem;
    display: block;
    border-radius: 1.25rem;
  }
  .banner img{
    width: 100%;
  }
  .listInfo{
    position: relative;
    z-index: 2;
    margin-left: 3%;
    padding-bottom: .4rem;
    margin-top: -2.75rem;
    width: 94%;
    border-radius: .5rem;
    background-color: #FFFFFF;
  }
  .trainTitle{
    text-align: center;
    font-size: .9rem;
    line-height: 2.45rem;
  }
  .banner span{
    position: fixed;
    top: .75rem;
    left: .75rem;
    background-color: rgba(0 ,0 ,0,.3);
    border-radius: 1rem;
    width:2rem;
    height: 2rem;
    line-height: 2rem;
    text-align: center;
    & img {
      width: 35%;
      margin: 0 auto;
    }
  }
  .icon-fanhui{
    font-size: 1.45rem;
    color: #FFFFFF;
    line-height: 2rem;
  }
  .iconfont {
    font-size: 2.15rem;
  }
</style>


